package cn.waqwb.bwcar.controller;

import cn.waqwb.bwcar.dto.ArticleDTO;
import cn.waqwb.bwcar.dto.DataGridResult;
import cn.waqwb.bwcar.dto.QueryDTO;
import cn.waqwb.bwcar.pojo.Article;
import cn.waqwb.bwcar.service.ArticleService;
import cn.waqwb.bwcar.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @author JokerQ
 * @date 2019/11/18 - 16:46
 */
@RestController
public class ArticleController {
    @Autowired
    private ArticleService articleService;

    @RequestMapping("/sys/article/list")
    private DataGridResult findArtittle(QueryDTO queryDTO){
        return articleService.findByPage(queryDTO);
    }

    @RequestMapping("/sys/article/del")
    private R delArtittle(@RequestBody List<Long> ids){
        for (Long id: ids
             ) {
            articleService.delArticle(id);
        }
        return R.ok();
    }

    @RequestMapping("/sys/article/info/{id}")
    private R findById(@PathVariable("id") Long id){
        Article byId = articleService.findById(id);
        return R.ok().put("article",byId);
    }

    @RequestMapping("/sys/article/save")
    private R addArtitle(@RequestBody ArticleDTO articleDTO){
        int i = articleService.addArticle(articleDTO);
        return i>0?R.ok():R.error("添加失败");
    }

    @RequestMapping("/sys/article/update")
    private R updateArtitle(@RequestBody ArticleDTO articleDTO){
        int i = articleService.updateArticle(articleDTO);
        return i>0?R.ok():R.error("修改失败");
    }

    @RequestMapping("/ytupload")
    private R upload(@RequestParam("mypic") MultipartFile multipartFile, HttpServletRequest request){
        //得到文件名称
        String filename = multipartFile.getOriginalFilename();
        //上传位置,不做分布式，只存在本地,不考虑文件名重复问题
        File dest = new File("E:\\IdeaProject\\bwcar\\src\\main\\java\\cn\\waqwb\\bwcar\\dest"+filename);
        try {
            multipartFile.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.ok().put("file",filename);
    }

}
